package com.wang.jmonkey.common.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wang.jmonkey.common.constant.SecurityConstant;
import com.wang.jmonkey.common.model.vo.UserVo;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @Description 登陆用户信息工具类
 * @Author HeJiawang
 * @Date 2021/5/20 20:13
 */
public final class UserUtil {

    private static final ThreadLocal<UserVo> THREAD_LOCAL_USER = new ThreadLocal<>();

    public static void setUser(UserVo user) {
        THREAD_LOCAL_USER.set(user);
    }

    public static UserVo getUser() {
        return Optional.ofNullable(THREAD_LOCAL_USER.get())
                .orElse(new UserVo());
    }

    public static void clearUser() {
        THREAD_LOCAL_USER.remove();
    }

    /**
     * 用户信息
     */
    public static final class Info {

        public static String getUsername() {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (ObjectUtil.isEmpty(attributes)) return StrUtil.EMPTY;

            HttpServletRequest request = attributes.getRequest();
            return getUsername(request);
        }

        /**
         * 获取发送请求的用户登陆名称
         * @param request http 请求
         * @return 用户登陆名称
         */
        public static String getUsername(HttpServletRequest request) {
            if (ObjectUtil.isEmpty(request)) return StrUtil.EMPTY;

            String authorization = request.getHeader(SecurityConstant.AuthKey.AUTHORIZATION.getKey());
            if (StrUtil.isEmpty(authorization)) return StrUtil.EMPTY;

            String token = request.getHeader(SecurityConstant.AuthKey.AUTHORIZATION.getKey());
            token = token.substring(SecurityConstant.AuthKey.BearerSpace.getKey().length());
            if (StrUtil.isEmpty(token)) return StrUtil.EMPTY;

            return getUsername(token);
        }

        /**
         * 获取token中的用户登陆名称
         * @param accessToken token
         * @return 用户登陆名称
         */
        public static String getUsername(String accessToken) {
            Jwt jwt = JwtHelper.decode(accessToken);
            JSONObject jsonObject = JSON.parseObject(jwt.getClaims());
            return jsonObject.getString(SecurityConstant.JwtContentKey.USER_NAME.getKey());
        }
    }
}
